#include <iostream>
#include <pthread.h> // 编译时需要连接pthread库
#include <unistd.h>

int g_val = 10;

void *threadRoutine(void *args)
{
    const char *name = (const char*)args;
    int cnt = 10;
    while (cnt--)
    {
        ++g_val;
        printf("%s, g_val: %d, pid: %d, thread_id: %p\n", name, g_val, getpid(), pthread_self());
        sleep(1);
    }
    return (void*)1;
    // return nullptr;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, threadRoutine, (void*)"Thread 1");  // 不是系统调用
    
    sleep(1);
    int cnt = 5;
    while (cnt--)
    {
        ++g_val;
        std::cout << "main thread, g_val: " << g_val << std::endl;
        sleep(1);
    }

    // 手动结束线程的方式
    // 1. 线程内return (void*)..
    // 2. 线程内pthread_exit((void*)..) or pthread_cancel(pthread_self());
    // 3. 线程外pthread_cancel(tid);

    void* retval;
    // &retval是输出型参数，用来接收线程返回值。不用考虑异常(状态)，因为线程异常，整个进程就异常了
    // pthread_join默认是阻塞等待的！
    pthread_join(tid, &retval);  

    std::cout << "main thread quit ..., ret: " << (long long int)retval << std::endl; // 将返回值转换为整数
    return 0;
}